package com.whz.work.ex02;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


/**
 * @ClassName HttpServer1
 * @Description TODO Servlet容器
 * @Author hong-zhi
 * @Date 2021/5/28 21:12
 * @Version 1.0
 */
@Slf4j
public class HttpServer1 {
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";

    private boolean shutdown = false;

    public static void main(String[] args) {
        HttpServer1 server = new HttpServer1();
        server.await();
    }

    public void await() {
        ServerSocket serverSocket = null;
        int port = 8080;
        try {
            /*创建一个ServerSocket等待接收请求*/
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        while (!shutdown) {
            try {
                Socket socket = serverSocket.accept();
                InputStream input = socket.getInputStream();
                OutputStream output = socket.getOutputStream();

                Request request = new Request(input);
                request.parse();


                Response response = new Response(output);
                response.setRequest(request);


                log.info("得到的uri: {}", request.getUri());
                if(StringUtils.isBlank(request.getUri()) || StringUtils.equals("/", request.getUri())) {
                    String encoding = response.getCharacterEncoding();
                    log.info("response.getCharacterEncoding(): {}", encoding);
                    PrintWriter writer = response.getWriter();

                    String result = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 123\r\n";
                    writer.println(result);
                    writer.close();
                } else {
                     if(request.getUri().startsWith("/servlet/")) {
                        ServletProcessor1 processor = new ServletProcessor1();
                        processor.process(request, response);
                    } else {
                        StaticResourceProcessor processor = new StaticResourceProcessor();
                        processor.process(request, response);
                    }
                }
                socket.close();
                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }
}
